package com.tianji.remark.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;
import static com.tianji.remark.constans.RedisConstants.LIKES_BIZ_KEY_PREFIX;
import static com.tianji.remark.constans.RedisConstants.LIKES_TIME_KEY_PREFIX;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2024-06-28
 */
@Service
@RequiredArgsConstructor
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final RabbitMqHelper mqHelper;
    private final StringRedisTemplate redisTemplate;

    /**
     * 1、点赞或者取消点赞（Day6 - 课堂）
     *
     * @param recordFormDTO
     */
    @Override
    public void addLikeRecord(LikeRecordFormDTO recordFormDTO) {
        // 1、基于前端参数，判断是点赞还是取消点赞，根据判断结果，执行点赞、取消点赞
        boolean isSuccess = recordFormDTO.getLiked() ? like(recordFormDTO) : unLike(recordFormDTO);

        // 2、判断是否执行成功，如果失败，直接结束
        if (!isSuccess) {
            return;
        }

        // 3、如果执行成功，统计点赞数
        Long likeTimes = redisTemplate.opsForSet().size(LIKES_BIZ_KEY_PREFIX + recordFormDTO.getBizId());

        // 4、缓存点赞总数到redis zset结构
        redisTemplate.opsForZSet().add(LIKES_TIME_KEY_PREFIX + recordFormDTO.getBizType(),
                recordFormDTO.getBizId().toString(), likeTimes);
    }

    /**
     * 2、根据业务ID集合查询点赞状态（Day6 - 课堂）
     *
     * @param bizIds
     */
    @Override
    public Set<Long> isLiked(List<Long> bizIds) {  // [1,2,3,4]
        // 1、获取当前登录人ID
        Long userId = UserContext.getUser();

        // 2、批量查询点赞状态
        /*Set<Long> ids = new HashSet<>(bizIds.size());
        for (Long bizId : bizIds){
            if (redisTemplate.opsForSet().isMember(LIKES_BIZ_KEY_PREFIX + bizId, userId.toString())){
                // 3、如果当前用户已经点赞，则返回true
                ids.add(bizId);
            }
        }
        return ids;*/

        // [true,false,false,true]
        List<Object> pipelinedResultList = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection connect = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                connect.sIsMember(LIKES_BIZ_KEY_PREFIX + bizId, userId.toString());
            }
            return null;
        });

        // 3、提取点赞过的业务ID，并返回
        /*Set<Long> ids = new HashSet<>(bizIds.size());
        for (int i = 0; i < pipelinedResultList.size(); i++) {
            Boolean o = (Boolean)pipelinedResultList.get(i);
            if(o){
                Long bizId = bizIds.get(i);
                ids.add(bizId);
            }
        }
        return ids;*/

        return IntStream.range(0, pipelinedResultList.size())
                .filter(i -> (Boolean) pipelinedResultList.get(i))
                .mapToObj(i -> bizIds.get(i))
                .collect(Collectors.toSet());
    }

    /**
     * 3、定时读取zset中的点赞数信息并且发送消息至业务方（更新点赞数）
     *
     * @param bizType
     * @param maxBizSize
     */
    @Override
    public void readLikeTimesAndSendMessage(String bizType, Integer maxBizSize) {
        // 1、批量读取redis zset中缓存的点赞总数（元组）
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(LIKES_TIME_KEY_PREFIX + bizType, maxBizSize);

        // 2、数据转换
        while(ObjectUtil.isNotEmpty(typedTuples)){
            List<LikedTimesDTO> messages = new ArrayList<>(typedTuples.size());
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                String bizId = typedTuple.getValue();
                Double likeTimes = typedTuple.getScore();
                messages.add(LikedTimesDTO.of(Long.valueOf(bizId), likeTimes.intValue()));
            }

            // 3、发送MQ消息
            mqHelper.send(LIKE_RECORD_EXCHANGE,
                    StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,bizType),
                    messages
            );

            // 4、继续查询下一轮（30条数据）
            typedTuples = redisTemplate.opsForZSet().popMin(LIKES_TIME_KEY_PREFIX + bizType, maxBizSize);
        }
    }

    /**
     * 取消点赞
     *
     * @param recordFormDTO
     * @return
     */
    private boolean unLike(LikeRecordFormDTO recordFormDTO) {
        // 1、组装大key
        String key = LIKES_BIZ_KEY_PREFIX + recordFormDTO.getBizId();

        // 2、执行set结构的 sadd命令，添加点赞人id到点赞set集合中
        Long result = redisTemplate.opsForSet().remove(key, UserContext.getUser().toString());

        // 3、返回是否成功
        return result !=null && result > 0;
    }

    /**
     * 点赞
     *
     * @param recordFormDTO
     * @return
     */
    private boolean like(LikeRecordFormDTO recordFormDTO) {
        // 1、组装大key
        String key = LIKES_BIZ_KEY_PREFIX + recordFormDTO.getBizId();

        // 2、执行set结构的 sadd命令，添加点赞人id到点赞set集合中
        Long result = redisTemplate.opsForSet().add(key, UserContext.getUser().toString());

        // 3、返回是否成功
        return result !=null && result > 0;
    }
}
